// Copyright 2015 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"flag"
	"fmt"
	"go.uber.org/atomic"
	"net/url"
	"time"
	"wths/wthsjy-im/plugins/log"
	"wths/wthsjy-im/protocol"

	"github.com/gorilla/websocket"
)

var addr = flag.String("addr", "101.34.7.166:9000", "http service address")

func main() {
	u := url.URL{Scheme: "ws", Host: *addr, Path: ""}
	log.Debug("ws").Msg("connecting to %s", u.String())

	c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
	if err != nil {
		log.Debug("ws").Msg("dial:", err)
	}
	defer c.Close()

	err = c.WriteMessage(websocket.BinaryMessage, getAuthPacketBytes())
	if err != nil {
		log.Debug("ws").Msg("write:", err)
		return
	}
	_, bs, err := c.ReadMessage()
	if err != nil {
		log.Error("ws").Msg("ReadIO:", err)
		return
	}

	p, err := protocol.Decode(bs)
	if err != nil {
		log.Error("ws").Msg("ReadIO:", err)
		return
	}
	log.Debug("ws").Msg(p.Head(), string(p.Data()))

	err = c.WriteMessage(websocket.BinaryMessage, getSubscribePacketBytes())
	if err != nil {
		log.Error("ws").Msg("write:", err)
		return
	}
	log.Debug("ws").Msg("~~~")

	for {
		_, bs, err = c.ReadMessage()
		if err != nil {
			log.Error("ws").Msg("ReadIO:", err)
			return
		}

		p, err = protocol.Decode(bs)
		if err != nil {
			log.Error("ws").Msg("ReadIO:", err)
			return
		}
		log.Debug("ws").Msg(p.Head(), string(p.Data()))
	}

}

var st = time.Now().UnixNano()
var index atomic.Int64

func getAuthPacketBytes() []byte {
	p, _ := protocol.NewConnectPacket(fmt.Sprintf("client_%d_%d", st, index.Add(1)), false)
	bs, _ := protocol.Encode(p)
	log.Debug("getAuthPacketBytes").Msg(len(bs))
	return bs
}
func getSubscribePacketBytes() []byte {
	p, _ := protocol.NewSubscribePacket([]string{"topic111"})
	//p, _ := protocol.NewSubscribePacket([]string{fmt.Sprintf("topic_%d", time.Now().UnixNano())})
	bs, _ := protocol.Encode(p)
	log.Debug("getSubscribePacketBytes").Msg(len(bs))
	return bs
}
